<!-- +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+----------------------------------------------------------------------
| 登录 开发者: 麦沃德科技-半夏
+---------------------------------------------------------------------- -->

<template>
	<view class="container" :style="{'--theme-color': themeColor}" v-if="loadEnd">
		<!-- 标题栏 -->
		<title-bar :showBack="true" positionMode="fixed" :backgroundColor="titleBackground"></title-bar>
		<!-- 顶部背景 -->
		<image class="container-bg" src="/static/login_bg.png" mode="widthFix"></image>
		<!-- 页面内容 -->
		<view class="container-main" :style="{paddingTop: titleBarHeight + 'px'}">
			<view class="main-info">
				<image class="info-logo" :src="loginImg" mode="widthFix"></image>
				<view class="info-title">嗨，欢迎使用{{appletName}}</view>
				<view class="info-subtitle">登录后为您带来更加流畅、高效的使用体验</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="main-login">
				<!-- 授权登录 -->
				<view class="login-info" v-if="isRegister">
					<view class="info-btn" @click="handleLogin">授权登录</view>
					<view class="info-btn cancel" @click="goBack(2)">取消登录</view>
				</view>
				<!-- 手机号 -->
				<view class="login-info" v-else-if="!isShowInfo">
					<button class="info-btn" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">授权手机号</button>
					<button class="info-btn cancel" @click="goBack(2)">取消登录</button>
				</view>
				<!-- 授权头像昵称 -->
				<form class="login-info" @submit="handleUpdateUser" v-else>
					<view class="info-item">
						<view class="item-title">头像</view>
						<button class="item-avatar" open-type="chooseAvatar" @chooseavatar="bindChooseAvatar">
							<image class="image" :src="avatarPath || '/static/login.png'" mode="aspectFill"></image>
						</button>
					</view>
					<view class="info-item">
						<view class="item-title">昵称</view>
						<input class="item-nickname" type="nickname" name="nickname" :value="userInfo.nickname" placeholder="请输入昵称" />
					</view>
					<button class="info-btn" style="margin-top: 48rpx;" form-type="submit">授权登录</button>
					<button class="info-btn cancel" @click="goBack(1)">稍后授权</button>
				</form>
				<!-- 底部安全区 -->
				<view class="safe-padding"></view>
			</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<!-- 手机号验证码登录 -->
			<view class="main-form" v-if="!isShowInfo">
				<view class="form-input">
					<input class="input" v-model="mobile" maxlength="11" type="number" placeholder="请输入您的手机号" placeholder-class="placeholder" />
				</view>
				<view class="form-input flex align-items-center">
					<input class="input flex-item" v-model="captcha" type="text" placeholder="请输入验证码" placeholder-class="placeholder" />
					<view class="countdown" v-if="countdown && countdown > 0">{{countdown}}秒</view>
					<view class="btn" @click="getCaptcha()" v-else>发送验证码</view>
				</view>
				<view class="form-btn" @click="onLogin">登录</view>
				<view class="form-read flex flex-center" @click="isRead = !isRead">
					<view class="radio" :class="{active: isRead}">
						<image src="/static/tick.png" mode="aspectFill" v-if="isRead"></image>
					</view>
					<view class="label flex-item">我已阅读并同意 <text class="text" @click.stop="toAgreement(3)">《用户协议》</text>和<text class="text" @click.stop="toAgreement(4)">《隐私政策》</text></view>
				</view>
			</view>
			<!-- 授权头像昵称 -->
			<view class="main-login" v-else>
				<view class="login-info">
					<view class="info-item">
						<view class="item-title">头像</view>
						<view class="item-avatar" @click="chooseAvatar">
							<image class="image" :src="avatarPath || '/static/login.png'" mode="aspectFill"></image>
						</view>
					</view>
					<view class="info-item">
						<view class="item-title">昵称</view>
						<input class="item-nickname" v-model="userInfo.nickname" placeholder="请输入昵称" />
					</view>
					<button class="info-btn" style="margin-top: 48rpx;" @click="handleUpdateUser">授权登录</button>
					<button class="info-btn cancel" @click="goBack(1)">稍后授权</button>
				</view>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import { mapState } from "vuex"
	import titleBar from "@/pages/component/title-bar/title-bar.vue"
	export default {
		components: {
			titleBar,
		},
		data() {
			return {
				// 加载完成
				loadEnd: false,
				// 标题栏高度
				titleBarHeight: 0,
				// 标题栏背景颜色
				titleBackground: "transparent",
				// 微信小程序登录参数
				// #ifdef MP-WEIXIN
				// 是否已经注册
				isRegister: false,
				// #endif
				// 已选择头像
				avatarPath: "",
				// 用户信息
				userInfo: {
					avatar: "",
					nickname: "",
				},
				// 手机号验证码登录参数
				// #ifndef MP-WEIXIN
				// 是否已读
				isRead: false,
				// 手机号
				mobile: "",
				// 验证码
				captcha: "",
				// 验证码倒计时
				countdown: 0,
				// 定时器
				interval: null,
				// #endif
				// 是否显示设置头像昵称
				isShowInfo: false,
			}
		},
		computed: {
			...mapState({
				themeColor: state => state.app.themeColor,
				appletName: state => state.app.appletName,
				loginImg: state => state.app.loginImg,
			})
		},
		mounted() {
			let statusBarHeight = 0
			// #ifdef MP-WEIXIN
			statusBarHeight = uni.getWindowInfo().statusBarHeight
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.titleBarHeight = (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height + statusBarHeight
			// #endif
			// #ifndef MP-WEIXIN
			statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.titleBarHeight = 48 + statusBarHeight
			// #endif
		},
		onLoad(option) {
			if (option.from) this.fromPage = decodeURIComponent(option.from)
			// #ifdef MP-WEIXIN
			uni.showLoading({
				title: "加载中"
			})
			this.getAuthStatus(() => {
				uni.hideLoading()
				this.loadEnd = true
			})
			// #endif
			// #ifndef MP-WEIXIN
			this.loadEnd = true
			// #endif
		},
		onPageScroll(e) {
			const scrollTop = e.scrollTop
			if (scrollTop > 100) {
				this.titleBackground = "#fff"
			} else {
				let opacity = parseFloat(scrollTop / 100).toFixed(4)
				this.titleBackground = "rgba(255, 255, 255, " + opacity + ")"
			}
		},
		// #ifndef MP-WEIXIN
		onUnload() {
			if (this.interval) clearInterval(this.interval)
		},
		// #endif
		methods: {
			// 返回上一页
			async goBack(type) {
				try {
					let pages = getCurrentPages()
					if (type == 2) {
						if (pages.length == 1 || pages[pages.length - 2].route.indexOf("pages/public/login/index") > -1) {
							this.$util.toPage({
								mode: 3,
								path: "/pages/passenger/index/index",
							})
						} else {
							uni.navigateBack()
						}
					} else {
						if (this.fromPage && this.fromPage.indexOf("pages/public/login/index") == -1) {
							this.$util.toPage({
								mode: 2,
								path: this.fromPage
							})
						} else {
							if (pages.length == 1 || pages[pages.length - 2].route.indexOf("pages/public/login/index") > -1) {
								this.$util.toPage({
									mode: 3,
									path: "/pages/passenger/index/index",
								})
							} else {
								uni.navigateBack()
							}
						}
					}
				} catch (error) {
					this.$util.toPage({
						mode: 3,
						path: "/pages/passenger/index/index",
					})
				}
			},
			// 微信登录
			// #ifdef MP-WEIXIN
			// 获取账号是否已注册
			getAuthStatus(fn) {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						this.$util.request("login.isAuth", {
							code: loginRes.code
						}).then(res => {
							if (fn) fn()
							if (res.code == 1) {
								if (res.data.auth_status == 1) {
									this.isRegister = true
								} else {
									this.isRegister = false
								}
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						}).catch(error => {
							if (fn) fn()
							console.error('获取账号是否已注册 ', error)
						})
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "授权失败，请重试"
						})
					}
				})
			},
			// 获取新的code并获取用户手机号码
			decryptPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					uni.showLoading({
						mask: true,
						title: "授权中"
					})
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							let data = e.detail
							data.code = loginRes.code
							this.$util.request("login.getPhone", data).then(res => {
								if (res.code == 1) {
									this.isRegister = res.data.auth_status == 1 ? true : false
									this.loginEvent(res.data.phoneNumber)
								} else {
									uni.hideLoading()
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}
							}).catch(error => {
								uni.hideLoading()
								console.error('获取用户手机号码 ', error)
							})
						}
					});
				} else {
					uni.showToast({
						title: '获取失败，请重新获取',
						duration: 1500,
						icon: 'none'
					})
				}
			},
			// 提交登录
			handleLogin() {
				uni.showLoading({
					title: '授权中',
					mask: true,
				})
				this.loginEvent()
			},
			// 提交登录
			loginEvent(mobile) {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						var url = this.isRegister ? "login.login" : "login.register"
						var data = {
							code: loginRes.code,
						}
						if (mobile) data.mobile = mobile
						if (!this.isRegister && uni.getStorageSync("wechat_id")) {
							data.parent_wechat_id = uni.getStorageSync("wechat_id")
						}
						this.$util.request(url, data).then(res => {
							uni.hideLoading()
							if (res.code == 1) {
								uni.setStorageSync('token', res.data.token);
								uni.setStorageSync("userInfo", res.data)
								this.$store.commit('user/setToken', res.data.token)
								this.$store.commit('user/setUserInfo', res.data)
								if (res.data.certification_examine_status == 2) this.$store.commit('app/setDriverSocket', 1)
								if (this.isRegister) this.goBack(1)
								else this.isShowInfo = true
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						}).catch(error => {
							uni.hideLoading()
							console.error('登录/注册 ', error)
						})
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "授权失败，请重试"
						})
					}
				})
			},
			// 选择头像
			bindChooseAvatar(e) {
				this.avatarPath = e.detail.avatarUrl
			},
			// #endif
			// 手机号验证码登录
			// #ifndef MP-WEIXIN
			// 跳转用户协议和隐私政策
			toAgreement(type) {
				this.$util.toPage({
					mode: 1,
					path: "/pages/driver/mine/settings/agreement?type=" + type
				})
			},
			// 获取验证码
			getCaptcha() {
				if (!this.mobile) {
					uni.showToast({
						icon: "none",
						title: "请输入手机号"
					})
					return
				}
				if (!this.$util.validation("phone", this.mobile)) {
					uni.showToast({
						icon: "none",
						title: "请输入正确的手机号"
					})
					return
				}
				uni.showLoading({
					title: "加载中",
					mask: true
				})
				this.$util.request("login.appCaptcha", {
					mobile: this.mobile,
					event: "mobilelogin",
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						clearInterval(this.interval)
						this.countdown = 60
						this.interval = setInterval(() => {
							if (this.countdown <= 1) {
								clearInterval(this.interval)
								this.countdown = 0
							} else this.countdown--
						}, 1000)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					uni.hideLoading()
					console.error('发送验证码', error)
				})
			},
			// 登录
			onLogin() {
				if (!this.isRead) {
					uni.showToast({
						icon: "none",
						title: "请阅读并同意用户协议和隐私政策"
					})
					return
				}
				if (!this.mobile) {
					uni.showToast({
						icon: "none",
						title: "请输入手机号"
					})
					return
				}
				if (!this.$util.validation("phone", this.mobile)) {
					uni.showToast({
						icon: "none",
						title: "请输入正确的手机号"
					})
					return
				}
				if (!this.captcha) {
					uni.showToast({
						icon: "none",
						title: "请输入手机验证码"
					})
					return
				}
				uni.showLoading({
					title: "登录中",
					mask: true
				})
				this.$util.request("login.appLogin", {
					mobile: this.mobile,
					captcha: this.captcha,
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync("userInfo", res.data)
						this.$store.commit('user/setToken', res.data.token)
						this.$store.commit('user/setUserInfo', res.data)
						this.$store.commit('app/setDriverSocket', 1)
						if (res.data.register_state == 1) this.isShowInfo = true
						else this.goBack(1)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					uni.hideLoading()
					console.error('登录/注册 ', error)
				})
			},
			// 选择头像
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success: (res) => {
						this.avatarPath = res.tempFilePaths[0]
					}
				});
			},
			// #endif
			// 修改头像昵称
			handleUpdateUser(e) {
				// #ifdef MP-WEIXIN
				this.userInfo.nickname = e.detail.value.nickname
				// #endif
				if (!this.avatarPath) {
					uni.showToast({
						title: "头像不能为空",
						icon: 'none',
					})
					return
				}
				if (!this.userInfo.nickname) {
					uni.showToast({
						title: "昵称不能为空",
						icon: 'none',
					})
					return
				}
				uni.showLoading({
					title: '授权中',
					mask: true,
				})
				this.$util.uploadFile(this.avatarPath).then(result => {
					this.userInfo.avatar = result.data.url
					this.$util.request("login.updateUser", this.userInfo).then(res => {
						uni.hideLoading()
						if (res.code == 1) {
							var userInfo = uni.getStorageSync("userInfo")
							userInfo.avatar = res.data.avatar
							userInfo.nickname = res.data.nickname
							uni.setStorageSync("userInfo", userInfo)
							this.$store.commit('user/setUserInfo', userInfo)
							this.goBack(1)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					}).catch(error => {
						uni.hideLoading()
						console.error('更新用户信息 ' + error)
					})
				}).catch(error => {
					uni.hideLoading()
					console.error('上传图片 ', error)
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #F7F7F7;
		padding-bottom: 0;
	}

	.container {
		.container-bg {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			width: 100%;
			height: auto;
		}

		.container-main {
			position: relative;
			z-index: 1;
			min-height: 100vh;
			display: flex;
			flex-direction: column;

			.main-info {
				padding-top: 80rpx;

				.info-logo {
					width: 240rpx;
					height: auto;
					margin: 0 auto;
				}

				.info-title {
					color: #242629;
					font-size: 20px;
					text-align: center;
					font-weight: 600;
					line-height: 56rpx;
					margin-top: 48rpx;
				}

				.info-subtitle {
					color: #8D929C;
					font-size: 28rpx;
					text-align: center;
					line-height: 40rpx;
					margin-top: 16rpx;
				}
			}

			.main-login {
				flex: 1;
				padding: 32rpx;
				margin-top: 120rpx;
				border-radius: 32rpx 32rpx 0 0;
				background: #FFF;

				.login-info {
					.info-item {
						display: flex;
						align-items: center;
						background: #ffffff;
						border-bottom: 1rpx solid rgba(0, 0, 0, 0.10);
						padding: 0 24rpx;

						.item-title {
							margin-right: 40rpx;
							font-size: 28rpx;
							line-height: 40rpx;
							color: #242629;
						}

						.item-avatar {
							flex: 1;
							padding: 32rpx 0;
							height: 80rpx;
							background: transparent;
							box-sizing: content-box;
							display: flex;
							justify-content: flex-start;

							&::after {
								border: none;
							}

							.image {
								width: 80rpx;
								height: 80rpx;
								border-radius: 50%;
							}
						}

						.item-nickname {
							flex: 1;
							font-size: 28rpx;
							line-height: 40rpx;
							padding: 32rpx 0;
							box-sizing: content-box;
						}
					}

					.info-btn {
						font-size: 28rpx;
						line-height: 40rpx;
						color: #ffffff;
						text-align: center;
						padding: 36rpx 32rpx;
						border-radius: 32rpx;
						background: var(--theme-color);
						margin-top: 32rpx;

						&:first-child {
							margin-top: 0;
						}

						&.cancel {
							background: #F6F7FB;
							color: var(--theme-color);
						}
					}
				}
			}

			.main-form {
				flex: 1;
				padding: 32rpx;
				margin-top: 48rpx;
				border-radius: 32rpx 32rpx 0 0;
				background: #FFF;

				.form-input {
					border-radius: 16rpx;
					background: #F6F7FB;
					margin-top: 32rpx;

					&:first-child {
						margin-top: 0;
					}

					.input {
						color: #5A5B6E;
						font-size: 28rpx;
						line-height: 40rpx;
						padding: 36rpx 32rpx;
					}

					.placeholder {
						color: #ACADB7;
					}

					.btn {
						padding: 0 24rpx;
						color: var(--theme-color);
						font-size: 28rpx;
						line-height: 40rpx;
					}

					.countdown {
						padding: 0 24rpx;
						color: #666;
						font-size: 28rpx;
						line-height: 40rpx;
					}
				}

				.form-btn {
					color: #FFF;
					font-size: 28rpx;
					line-height: 40rpx;
					padding: 36rpx;
					border-radius: 16rpx;
					background: var(--theme-color);
					margin-top: 48rpx;
					text-align: center;
				}

				.form-read {
					margin-top: 52rpx;

					.radio {
						width: 32rpx;
						height: 32rpx;
						background: #D6DBDE;
						border-radius: 50%;

						&.active {
							background: var(--theme-color);
						}
					}

					.label {
						margin-left: 20rpx;
						color: #5A5B6E;
						font-size: 24rpx;
						line-height: 34rpx;

						.text {
							color: var(--theme-color);
						}
					}
				}
			}
		}
	}
</style>